﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;

namespace QLThuChi.OtherForms
{
    #region Using
    using QLThuChi.Models;
    using QLThuChi.Repositories;
    using QLThuChi.Helpers;
    #endregion

    /// <summary>
    /// tuansl added: insert new khenthuong progress
    /// </summary>
    public partial class FrmLapPhieuThu : DevComponents.DotNetBar.Office2007Form
    {
        private EnumUpdateMode UpdateMode = EnumUpdateMode.INSERT;
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaCongTrinhGiaiDoan;
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaPhieu;

        public FrmLapPhieuThu(int magiaidoan)
        {
            InitializeComponent();
            InitHiddenFields();

            txtMaCongTrinhGiaiDoan.Text = magiaidoan.ToString();
            var giaidoan = CongTrinh_GiaiDoanRepository.SelectByID(int.Parse(txtMaCongTrinhGiaiDoan.Text));
            txtCongTrinh.Text = giaidoan.CongTrinh.TenCongTrinh;
            txtGiaiDoan.Text = giaidoan.GiaiDoan.TenGiaiDoan;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            UpdateMode = EnumUpdateMode.INSERT;
            EraseTextboxes();
            SetDefaultMode(false);
            DisableCmdButtons();
            txtSoTien.Focus();
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            if (txtMaPhieu.Text != "")
            {
                UpdateMode = EnumUpdateMode.UPDATE;
                SetDefaultMode(false);
                DisableCmdButtons();
                txtSoTien.Focus();
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (txtMaPhieu.Text != "")
            {
                if (MessageBox.Show("Bạn có chắc chắn xóa dữ liệu này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (PhieuThuRepository.Delete(int.Parse(txtMaPhieu.Text)))
                    {
                        EraseTextboxes();
                        txtMaPhieu.Text = "";
                        LoadData();
                        MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void btnGhi_Click(object sender, EventArgs e)
        {
            string errorText = "";
            var success = false;

            if (!ValidateUserInput(ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (UpdateMode == EnumUpdateMode.INSERT)
            {
                if (ActionAdd())
                {
                    success = true;
                }
            }
            else if (UpdateMode == EnumUpdateMode.UPDATE)
            {
                if (ActionUpdate())
                {
                    success = true;
                }
            }
            // Inform result for nguoidung
            if (success)
            {
                LoadData();
                SetDefaultMode(true);
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            // Case 1
            if (txtMaPhieu.Text != "")
                LoadCurrentQuaTrinhInfo(int.Parse(txtMaPhieu.Text));
            else
                EraseTextboxes();

            SetDefaultMode(true);
            btnThem.Focus();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmNhapQuaTrinhKhenThuong_Load(object sender, EventArgs e)
        {
            LoadData();
            EraseTextboxes();
            SetDefaultMode(true);
            txtNgayLapPhieu.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
        }

        private void lstvData_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstvData.SelectedItems.Count > 0)
            {
                var item = (PhieuThu)lstvData.SelectedItems[0].Tag;

                txtMaPhieu.Text = item.MaPhieu.ToString();
                txtSoTien.Text = item.SoTien.ToString();
                txtLyDo.Text = item.LyDo;
                txtNgayLapPhieu.Text = String.Format("{0:dd/MM/yyyy}", item.NgayLapPhieu.Value);
            }
        }

        private void FrmNhapQuaTrinhKhenThuong_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        /// <summary>
        /// Load list of congtac progresses of specified nhanvien
        /// </summary>
        public void LoadData()
        {
            var lstItem = PhieuThuRepository.SelectByMaCongTrinhGiaiDoan(int.Parse(txtMaCongTrinhGiaiDoan.Text));
            lstvData.Items.Clear();
            for (int i = 0; i < lstItem.Count; i++)
            {
                var objListViewItem = new ListViewItem();
                objListViewItem.Tag = lstItem[i];
                objListViewItem.Text = (i + 1).ToString();
                objListViewItem.SubItems.Add(String.Format("{0:dd/MM/yyyy}", lstItem[i].NgayLapPhieu.Value));
                lstvData.Items.Add(objListViewItem);
            }
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaCongTrinhGiaiDoan = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaCongTrinhGiaiDoan",
                Text = ""
            };
            txtMaCongTrinhGiaiDoan.Visible = false;

            // Add a new textbox
            txtMaPhieu = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaPhieu",
                Text = ""
            };
            txtMaPhieu.Visible = false;
        }

        /// <summary>
        /// Validate user inputs
        /// </summary>
        /// <returns></returns>
        public bool ValidateUserInput(ref string errorText)
        {
            if (txtSoTien.Text == "")
            {
                errorText = "Vui lòng nhập số tiền";
                return false;
            }
            return true;
        }

        /// <summary>
        /// Update foreign keys need to insert
        /// </summary>
        /// <param name="KhenThuong"></param>
        public void UpdateForeignKeys(ref PhieuThu item)
        {
            if (txtMaCongTrinhGiaiDoan.Text != "")
            {
                item.MaCongTrinhGiaiDoan = int.Parse(txtMaCongTrinhGiaiDoan.Text);
            }
            item.MaNguoiLapPhieu = GlobalVars.g_CurrentUser.MaNguoiDung;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var newItem = new PhieuThu
                {
                    SoTien = long.Parse(txtSoTien.Text.Contains(",") ? txtSoTien.Text.Replace(",", "") : txtSoTien.Text.Replace(".", "")),
                    LyDo = txtLyDo.Text,
                    NgayLapPhieu = DateTime.Now
                };

                UpdateForeignKeys(ref newItem);

                if (!PhieuThuRepository.Insert(newItem))
                {
                    return false;
                }
                RefreshQuaTrinh(newItem.MaPhieu.ToString());
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Update an item in DB
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = PhieuThuRepository.SelectByID(int.Parse(txtMaPhieu.Text));
                item.SoTien = long.Parse(txtSoTien.Text.Contains(",") ? txtSoTien.Text.Replace(",", "") : txtSoTien.Text.Replace(".", ""));
                item.LyDo = txtLyDo.Text;
                item.NgayLapPhieu = DateTime.Now;

                UpdateForeignKeys(ref item);

                return PhieuThuRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Load info of current quatrinh
        /// If mode is insert: update txtMaKhenThuong
        /// Else: not change
        /// </summary>
        public void LoadCurrentQuaTrinhInfo(int id)
        {
            var item = PhieuThuRepository.SelectByID(id);

            txtMaPhieu.Text = id.ToString();
            txtSoTien.Text = item.SoTien.ToString();
            txtLyDo.Text = item.LyDo;
            txtNgayLapPhieu.Text = String.Format("{0:dd/MM/yyyy}", item.NgayLapPhieu.Value);
        }

        /// <summary>
        /// Disable them, xoa, sua
        /// </summary>
        public void DisableCmdButtons()
        {
            btnThem.Enabled = false;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
        }

        /// <summary>
        /// Store ma qua trinh cong tac
        /// </summary>
        /// <param name="val"></param>
        public void RefreshQuaTrinh(string val)
        {
            txtMaPhieu.Text = val;
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtSoTien.Text = "";
            txtLyDo.Text = "";
        }

        /// <summary>
        /// Set default status
        /// </summary>
        /// <param name="val">default is true</param>
        public void SetDefaultMode(bool val = true)
        {
            txtLyDo.ReadOnly = val;
            txtSoTien.ReadOnly = val;

            btnThem.Enabled = val;
            btnSua.Enabled = val;
            btnXoa.Enabled = val;
            btnGhi.Enabled = !val;
            btnHuy.Enabled = !val;
        }

        private void FrmNhapQuaTrinhKhenThuong_Shown(object sender, EventArgs e)
        {
        }

        private void txtSoTien_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Only allow type number
            if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back)
            {
                e.Handled = true;
            }
        }

        // This variable is used to end changing on textbox
        private bool endChange = false;
        private void txtSoTien_TextChanged(object sender, EventArgs e)
        {
            if (endChange)
            {
                endChange = false;
                this.txtSoTien.SelectionStart = this.txtSoTien.Text.Length;
                return;
            }
            if (txtSoTien.Text.Length > 0)
            {
                var strOrigin = txtSoTien.Text.Contains(",") ? txtSoTien.Text.Replace(",", "") : txtSoTien.Text.Replace(".", "");
                var strFormated = String.Format("{0:#,##0;Nothing}", long.Parse(strOrigin));
                if (strOrigin != strFormated)
                {
                    endChange = true;
                    this.txtSoTien.Text = strFormated;
                }
            }
        }
    }
}